﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MalkiSumWeb.Models;
using System.Net.Mail;
using System.Text;
using System.IO;
using System.Globalization;

namespace MalkiSumWeb.Controllers
{
    public class AccountController : MainController
    {
        public ActionResult LogOff()
        {
            MainController.myUserName = "";
            MainController.myUserID = 0;
            MainController.myFirstName = "";
            MainController.myLastName = "";
            MainController.IsAuthenticated = false;

            return Redirect("~/Home/Index");
            //return View();
        }

        public ActionResult LogOn()
        {
            ViewBag.Message = "Welcome, please login or signup.";

            return View();
        }

        public ActionResult Followers()
        {
            SumrizDBEntities db = new SumrizDBEntities();
            var memberIDs = db.MemberActivities.Where(m => m.IsDeleted == false && m.ActionTypeID == 3 && m.Member2ID == MainController.myUserID).Select(m => m.MemberID).ToList();

            var memberActivities = db.MemberActivities
                .Where(m => m.IsDeleted == false && m.ActionTypeID == 3
                    && m.Member2ID == MainController.myUserID);

            var members = db.Members.Where(m => m.ID == memberIDs.Where(i => i == m.ID).FirstOrDefault());
            if (members.Count() > 0)
            {
                return View(memberActivities);
            }
            return View();
        }

        public ActionResult MyDocuments()
        {
            return View();
        }

        public ActionResult MyFavourites()
        {
            return View();
        }
        public ActionResult Profile()
        {
            SumrizDBEntities db = new SumrizDBEntities();
            var member = db.Members.Where(m => m.ID == MainController.myUserID).FirstOrDefault();
            if (member != null)
            {
                return View("Profile", member);
            }
            return View("Profile");
        }

        public JsonResult SaveProfile(int UserID, string FirstName, string LastName, string Username,
                string Gender, string BirthDate, string Location, string Website, string Bio, string TwitterID, string FacebookID)
        {
            bool success = false;

            SumrizDBEntities db = new SumrizDBEntities();
            var member = db.Members.Where(m => m.ID == UserID).FirstOrDefault();
            if (member != null)
            {
                member.FirstName = FirstName;
                member.LastName = LastName;
                //member.Username = Username;
                member.Gender = Gender == "1" ? true : false; ; // True = 1 = male, False = 0 = female
                DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
                dtfi.DateSeparator = "/";
                dtfi.ShortDatePattern = "MM/dd/yyyy";
                try
                {
                    member.BirthDate = Convert.ToDateTime(BirthDate, dtfi);
                }
                catch (Exception ex)
                {

                }
                member.Location = Location;
                member.Website = Website;
                member.Bio = Bio;
                member.TwitterID = TwitterID;
                member.FacebookID = FacebookID;
                db.SaveChanges();

                MainController.FillUser(UserID);
                success = true;


            }

            return Json(new
            {
                msg = "Unknown error!",
                FirstName = FirstName,
                LastName = LastName,
                Username = Username,
                Location = Location,
                Website = Website,
                Bio = Bio,
                TwitterID = TwitterID,
                FacebookID = FacebookID,
                success = success
            });
            //return Json(a, JsonRequestBehavior.AllowGet);
        }

        public JsonResult ResendPassword(string UserName)
        {
            bool success = false;

            SumrizDBEntities db = new SumrizDBEntities();
            var user = db.Members.Where(m => m.Username == UserName).FirstOrDefault();
            if (user != null)
            {
                try
                {

                    Uri uri = new Uri(Request.Url.AbsoluteUri);
                    string host = uri.Host;
                    SmtpClient smtp = new SmtpClient();
                    MailMessage msg = new MailMessage();

                    msg.From = new MailAddress("info@sumriz.global4web.com");

                    msg.To.Add(UserName);
                    msg.BodyEncoding = Encoding.GetEncoding("utf-8");
                    msg.Subject = " Account Password Reset ";
                    msg.Body = "<img src='http://" + uri.Host + "/Content/images/logo.jpg' /> <br/>";
                    msg.Body += "<div style='font-size:large;font-weight:bold;font-family:Arabic Transparent;' >";
                    msg.Body += " You have requested your password in Sumriz  " + "<br/>";

                    msg.Body += "User name = " + UserName + "<br/>";
                    msg.Body += "Password = " + user.CurrentPassword + "<br/>";
                    msg.Body += "</div>";
                    msg.IsBodyHtml = true;


                    smtp.Host = "mail.global4web.com";
                    smtp.Port = 2525;
                    smtp.EnableSsl = false;

                    smtp.Credentials = new System.Net.NetworkCredential("info@sumriz.global4web.com", "1234567*");
                    smtp.Send(msg);

                    success = true;
                }
                catch (Exception ex)
                {

                }
            }

            return Json(new
            {
                msg = "Inalide E-mail or password",
                success = success
            });
            //return Json(a, JsonRequestBehavior.AllowGet);
        }

        public JsonResult SignIn(string UserName, string Password)
        {
            bool success = false;

            if (MainController.ValidateUser(UserName, Password))
            {
                success = true;
            }
            return Json(new
            {
                msg = "Inalide E-mail or password",
                success = success
            });
            //return Json(a, JsonRequestBehavior.AllowGet);
        }

        public JsonResult SignUp(string UserFullName, string UserName, string Password)
        {
            bool success = false;
            SumrizDBEntities db = new SumrizDBEntities();
            Member memb = new Member();
            string ErrorMessage = "Unknown error";

            if (UserFullName.Trim() == "" || UserName.Trim() == "" || Password.Trim() == "")
            {
                ErrorMessage = "Type your name, E-mail and password first.";
                return Json(new
                {
                    msg = ErrorMessage,
                    success = success
                });
            }
            if (UserFullName.Trim().Contains(' '))
            {
                string[] fullName = UserFullName.Split(' ');
                if (fullName.Length > 1)
                {
                    memb.FirstName = fullName[0].ToString();
                    memb.LastName = fullName[1].ToString();
                }
            }
            else
            {
                memb.FirstName = UserFullName.Trim();
            }
            var otherMembers = db.Members.Select(m => m.Username).ToList();
            if (otherMembers.Count > 0)
            {
                foreach (string item in otherMembers)
                {
                    if (UserName.Trim() == item.Trim())
                    {
                        ErrorMessage = "Username is already exist.";
                        return Json(new
                        {
                            msg = ErrorMessage,
                            success = success
                        });
                    }
                }
            }
            memb.MemberStatusID = 10;
            memb.Username = UserName.Trim();
            memb.CurrentPassword = Password.Trim();
            db.Members.AddObject(memb);
            db.SaveChanges();

            if (memb.ID > 0)
            {
                send(memb.ID, memb.Username);
                success = true;
            }
            return Json(new
            {
                msg = ErrorMessage,
                success = success
            });
            //return Json(a, JsonRequestBehavior.AllowGet);
        }

        private IEnumerable<string> GetFileInfo(IEnumerable<HttpPostedFileBase> attachments)
        {
            return
                from a in attachments
                where a != null
                select string.Format("{0} ({1} bytes)", Path.GetFileName(a.FileName), a.ContentLength);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveProfileImage(IEnumerable<HttpPostedFileBase> attachments)
        {
            try
            {
                if (attachments != null)
                {
                    //TempData["UploadedAttachments"] = GetFileInfo(attachments);
                    IEnumerable<string> FileInfo = GetFileInfo(attachments);
                    foreach (var file in attachments)
                    {
                        if (!Directory.Exists(Server.MapPath("~/Content/Users/" + MainController.myUserID + "/Profile/")))
                        {
                            Directory.CreateDirectory(Server.MapPath("~/Content/Users/" + MainController.myUserID + "/Profile/"));
                        }

                        string FilePath = Server.MapPath("~/Content/Users/" + MainController.myUserID + "/Profile/" + Path.GetFileName(file.FileName));
                        file.SaveAs(FilePath);

                        SumrizDBEntities db = new SumrizDBEntities();
                        Models.Member user = db.Members.Where(m => m.ID == MainController.myUserID).FirstOrDefault();
                        if (user.PersonalImageUrl != "" && user.PersonalImageUrl != Path.GetFileName(file.FileName))
                        {
                            System.IO.File.Delete(Server.MapPath("~/Content/Users/" + MainController.myUserID + "/Profile/" + user.PersonalImageUrl));
                        }
                        user.PersonalImageUrl = Path.GetFileName(file.FileName);
                        db.SaveChanges();

                        MainController.myPersonalImageUrl = Path.GetFileName(file.FileName);
                    }
                }
                else
                {
                    ViewData["error"] = "Select an image first";
                    ViewData["errorDetails"] = "";
                }
                return Profile();
            }
            catch (Exception ex)
            {
                ViewData["error"] = ex.Message;
                if (ex.InnerException != null)
                {
                    ViewData["errorDetails"] = ex.InnerException.Message;
                }

                return Profile();
            }

        }

        private void send(int ID, string Mail)
        {
            Uri uri = new Uri(Request.Url.AbsoluteUri);
            string host = uri.Host;
            SmtpClient smtp = new SmtpClient();
            MailMessage msg = new MailMessage();

            msg.From = new MailAddress("info@sumriz.global4web.com");

            msg.To.Add(Mail);
            msg.BodyEncoding = Encoding.GetEncoding("utf-8");
            msg.Subject = " Account Activation ";
            msg.Body = "<img src='http://" + uri.Host + "/Content/images/logo.jpg' /> <br/>";
            msg.Body += "<div style='font-size:large;font-weight:bold;font-family:Arabic Transparent;' >";
            msg.Body += " You have been registered to Sumriz  " + "<br/>" + "Click here to activate your accoumt." + "<br/>";

            msg.Body += "<a href='http://" + uri.Host + "/Account/Activate?code=" + ID + "&username=" + Mail + "' target='_blank' > http://" + uri.Host + "/Account/Activate?code=" + ID + "&username=" + Mail + " </a>" + "<br/>";
            msg.Body += "</div>";
            msg.IsBodyHtml = true;

            try
            {
                smtp.Host = "mail.global4web.com";
                smtp.Port = 2525;
                smtp.EnableSsl = false;

                smtp.Credentials = new System.Net.NetworkCredential("info@sumriz.global4web.com", "1234567*");
                smtp.Send(msg);
            }
            catch (Exception)
            {

            }


        }

        public ActionResult Activate(int code, string username)
        {
            SumrizDBEntities db = new SumrizDBEntities();
            var member = db.Members.Where(m => m.ID == code && m.Username == username.Trim()).FirstOrDefault();
            if (member != null)
            {
                member.MemberStatusID = 20;
                db.SaveChanges();

                MainController.FillUser(member.ID);
            }
            return Profile();
        }


    }
}
